package com.qdsgjsfk.vision.ui.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.base.BaseFragment;
import com.qdsgjsfk.vision.ui.dialog.RemarkDialog;
import com.qdsgjsfk.vision.util.Cn2Spell;
import com.qdsgjsfk.vision.util.IntentUtil;
import com.qdsgjsfk.vision.util.NetUtil;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.qdsgjsfk.vision.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.IaBaseResponse;
import com.rest.response.Student;
import com.rest.response.StudentResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;

/**
 * Created by HP on 2018/10/6.
 */

public class StudentListFragment extends BaseFragment {

    @BindView(R.id.recyclerView_student_list)
    RecyclerView recyclerView_student_list;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    @BindView(R.id.recyclerView_letter)
    RecyclerView recyclerView_letter;

    @BindView(R.id.className)
    TextView className;

    @BindView(R.id.status)
    TextView tv_status;

    List<Student> list = new ArrayList<>();
    List<Student> listWithLetter = new ArrayList<>();
    List<Student> listLetter = new ArrayList<>();

    private String taskId, classId;
    private int type;

    MyAdapter myAdapter;
    MyLetterAdapter myLetterAdapter;
    private boolean hasAxisExamineOption, hasOtherExamineOption;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_student_list;
    }

    @Override
    protected void initView() {
        myAdapter = new MyAdapter();
        recyclerView_student_list.setLayoutManager( new LinearLayoutManager( mContext ) );
        recyclerView_student_list.setAdapter( myAdapter );
        myLetterAdapter = new MyLetterAdapter();
        recyclerView_letter.setLayoutManager( new LinearLayoutManager( mContext ) );
        recyclerView_letter.setAdapter( myLetterAdapter );
        refreshLayout.setRefreshFooter( new BallPulseFooter( mContext ).setSpinnerStyle( SpinnerStyle.Scale ) );
        refreshLayout.setRefreshHeader( new ClassicsHeader( mContext ) );
        refreshLayout.setEnableLoadMore( false );
        refreshLayout.setOnRefreshListener( refreshlayout -> getStudentList( type ) );
        refreshLayout.setOnLoadMoreListener( refreshlayout -> {
        } );
    }

    @Override
    protected void initData() {
        assert getArguments() != null;
        classId = getArguments().getString( "classId" );
        type = getArguments().getInt( "type", -1 );
        taskId = getArguments().getString( "taskId" );
    }


    @Override
    public void onResume() {
        super.onResume();
        getStudentList( type );
    }

    public static StudentListFragment newInstance(int type, String classId, String taskId) {
        Bundle args = new Bundle();
        args.putInt( "type", type );
        args.putString( "classId", classId );
        args.putString( "taskId", taskId );
        StudentListFragment fragment = new StudentListFragment();
        fragment.setArguments( args );
        return fragment;
    }

    class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (viewType == 1) {//1 首字母  0学生
                return new LetterHolder( getLayoutInflater().inflate( R.layout.item_letter, parent, false ) );
            } else if (viewType == 0) {
                if (BaseApplication.isShowAxis && BaseApplication.isShowOther) {
                    return new StudentHolder( getLayoutInflater().inflate( R.layout.item_student_axis, parent, false ) );
                } else {
                    return new StudentHolder( getLayoutInflater().inflate( R.layout.item_student, parent, false ) );
                }

            }
            return null;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            if (holder instanceof LetterHolder) {
                ((LetterHolder) holder).tv_name.setText( listWithLetter.get( position ).letter );
            }
            if (holder instanceof StudentHolder) {
                if (listWithLetter.get( position - 1 ).type == 1) {
                    if (listWithLetter.size() <= position + 1) {
                        ((StudentHolder) holder).container.setBackgroundResource( R.drawable.round_white );
                        ((StudentHolder) holder).line.setVisibility( View.GONE );
                    } else {
                        if (listWithLetter.get( position + 1 ).type == 1) {
                            ((StudentHolder) holder).container.setBackgroundResource( R.drawable.round_white );
                            ((StudentHolder) holder).line.setVisibility( View.GONE );
                        } else {
                            ((StudentHolder) holder).container.setBackgroundResource( R.drawable.round_white_top );
                            ((StudentHolder) holder).line.setVisibility( View.VISIBLE );
                        }
                    }
                } else {
                    if (listWithLetter.size() <= position + 1) {
                        ((StudentHolder) holder).container.setBackgroundResource( R.drawable.round_white_bottom );
                        ((StudentHolder) holder).line.setVisibility( View.GONE );
                    } else {
                        if (listWithLetter.get( position + 1 ).type == 1) {
                            ((StudentHolder) holder).container.setBackgroundResource( R.drawable.round_white_bottom );
                            ((StudentHolder) holder).line.setVisibility( View.GONE );
                        } else {
                            ((StudentHolder) holder).container.setBackgroundColor( ContextCompat.getColor( requireContext(), R.color.white ) );
                            ((StudentHolder) holder).line.setVisibility( View.VISIBLE );
                        }
                    }
                }

                ((StudentHolder) holder).tv_name.setText( listWithLetter.get( position ).studentName );

                if (hasAxisExamineOption) {
                    ((StudentHolder) holder).ll_axis.setVisibility( View.VISIBLE );
                } else {
                    ((StudentHolder) holder).ll_axis.setVisibility( View.GONE );
                }
                if (hasOtherExamineOption) {
                    ((StudentHolder) holder).ll_other.setVisibility( View.VISIBLE );
                } else {
                    //不展示其他选项
                    ((StudentHolder) holder).ll_other.setVisibility( View.GONE );
                }

                if (listWithLetter.get( position ).checkAxis) {
                    ((StudentHolder) holder).img_axis.setImageResource( R.mipmap.selected );
                } else {
                    ((StudentHolder) holder).img_axis.setImageResource( R.mipmap.unselected );
                }
                if (listWithLetter.get( position ).checkOther) {
                    ((StudentHolder) holder).img_other.setImageResource( R.mipmap.selected );
                } else {
                    ((StudentHolder) holder).img_other.setImageResource( R.mipmap.unselected );
                }

                if (!UtilString.isEmpty( listWithLetter.get( position ).notExamReason )) {
                    ((StudentHolder) holder).tv_reason.setVisibility( View.VISIBLE );
                    ((StudentHolder) holder).tv_reason.setText( listWithLetter.get( position ).notExamReason );
                } else {
                    ((StudentHolder) holder).tv_reason.setVisibility( View.INVISIBLE );
                }

                if (listWithLetter.get( position ).isCheck == 0) {
                    ((StudentHolder) holder).img_vision.setImageResource( R.mipmap.unselected );
                    ((StudentHolder) holder).img_diopter.setImageResource( R.mipmap.unselected );

                } else if (listWithLetter.get( position ).isCheck == 1) {
                    ((StudentHolder) holder).img_vision.setImageResource( R.mipmap.selected );
                    ((StudentHolder) holder).img_diopter.setImageResource( R.mipmap.unselected );
                } else if (listWithLetter.get( position ).isCheck == 2) {
                    ((StudentHolder) holder).img_vision.setImageResource( R.mipmap.unselected );
                    ((StudentHolder) holder).img_diopter.setImageResource( R.mipmap.selected );
                } else if (listWithLetter.get( position ).isCheck == 3) {
                    ((StudentHolder) holder).img_vision.setImageResource( R.mipmap.selected );
                    ((StudentHolder) holder).img_diopter.setImageResource( R.mipmap.selected );
                }


//                if(listWithLetter.get(position).diagnoseStatus.equals("1")){
//                    ((StudentHolder) holder).img_diagnose.setImageResource(R.mipmap.selected);
//                }else{
//                    ((StudentHolder) holder).img_diagnose.setImageResource(R.mipmap.unselected);
//                }
//                ((StudentHolder) holder).progressSelf.setProgress(listWithLetter.get(position).schedule);
//                ((StudentHolder) holder).examinationDate.setText(listWithLetter.get(position).examinationDate);
                ((StudentHolder) holder).itemView.setOnClickListener( v -> {

                    if (hasOtherExamineOption || hasAxisExamineOption) {
                        //有其他选项
                        IntentUtil.ToStudentDetailOtherActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 0, listWithLetter.get( position ).notExamReason );
                    } else {
                        IntentUtil.ToStudentDetailActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 0, listWithLetter.get( position ).notExamReason );
                    }


                } );

                ((StudentHolder) holder).ll_vision.setOnClickListener( v -> {
                    if (hasOtherExamineOption || hasAxisExamineOption) {
                        //有其他选项
                        IntentUtil.ToStudentDetailOtherActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 0, listWithLetter.get( position ).notExamReason );

                    } else {
                        IntentUtil.ToStudentDetailActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 0, listWithLetter.get( position ).notExamReason );
                    }

                } );

                ((StudentHolder) holder).ll_diopter.setOnClickListener( v -> {
                    if (hasOtherExamineOption || hasAxisExamineOption) {
                        //有其他选项
                        IntentUtil.ToStudentDetailOtherActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 1, listWithLetter.get( position ).notExamReason );

                    } else {
                        IntentUtil.ToStudentDetailActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 1, listWithLetter.get( position ).notExamReason );
                    }

                } );

                ((StudentHolder) holder).ll_other.setOnClickListener( v -> {
                    if (hasAxisExamineOption) {
                        IntentUtil.ToStudentDetailOtherActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 3, listWithLetter.get( position ).notExamReason );
                    } else {
                        IntentUtil.ToStudentDetailOtherActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 2, listWithLetter.get( position ).notExamReason );
                    }


                } );
                ((StudentHolder) holder).ll_axis.setOnClickListener( v -> {
                    IntentUtil.ToStudentDetailOtherActivity( getActivity(), listWithLetter.get( position ).studentId, taskId, 2, listWithLetter.get( position ).notExamReason );

                } );

                ((StudentHolder) holder).ll_reason.setOnClickListener( v -> {
                    RemarkDialog mRemarkDialog = null;

                    if (mRemarkDialog == null) {
                        //原因为空，不显示清空按钮
                        if (!UtilString.isEmpty( listWithLetter.get( position ).notExamReason )) {
                            mRemarkDialog = RemarkDialog.newInstance( true, true );
                        } else {
                            mRemarkDialog = RemarkDialog.newInstance( false, true );
                        }

                        mRemarkDialog.show( getChildFragmentManager(), "mRemarkDialog" );
                        RemarkDialog finalMRemarkDialog = mRemarkDialog;
                        final String[] notExamReason = new String[1];
                        mRemarkDialog.setmListener( (reason, typeConfirm) -> {
                            if (!UtilString.isEmpty( reason )) {
                                notExamReason[0] = reason;
                                ((StudentHolder) holder).tv_reason.setVisibility( View.VISIBLE );
                                ((StudentHolder) holder).tv_reason.setText( reason );
                            } else {
                                //清空
                                notExamReason[0] = "";
                                ((StudentHolder) holder).tv_reason.setVisibility( View.INVISIBLE );
                            }
                            RestProxy.getInstance().notExamReason( taskId, listWithLetter.get( position ).studentId, notExamReason[0], new Observer<IaBaseResponse>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(IaBaseResponse iaBaseResponse) {
                                    finalMRemarkDialog.dismiss();
                                    getStudentList( type );
                                }

                                @Override
                                public void onError(Throwable e) {
                                    finalMRemarkDialog.dismiss();
                                    e.printStackTrace();
                                    NetUtil.onError( e, mContext );
                                }

                                @Override
                                public void onComplete() {

                                }
                            } );


                        } );
                    } else if (!mRemarkDialog.isAdded() && !mRemarkDialog.isShowing()) {
                        mRemarkDialog.show( getChildFragmentManager(), "mRemarkDialog" );
                    }
                } );

                if (listWithLetter.get( position ).dataLegal) {
                    ((StudentHolder) holder).img.setVisibility( View.VISIBLE );
                } else {
                    ((StudentHolder) holder).img.setVisibility( View.INVISIBLE );
                }
                ((StudentHolder) holder).img.setOnClickListener( v -> Toast.makeText( mContext, "屈光与视力不匹配，建议重新检查", Toast.LENGTH_SHORT ).show() );
            }

        }

        @Override
        public int getItemCount() {
            return listWithLetter.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (listWithLetter.get( position ).type == 1) {
                return 1;
            } else {
                return 0;
            }
        }


        class StudentHolder extends RecyclerView.ViewHolder {
            TextView tv_name, tv_reason;
            ImageView img, img_vision, img_diopter, img_diagnose, img_axis, img_other;
            LinearLayout ll_vision, ll_diopter, ll_axis, ll_other, container, ll_reason;
            View line;

            StudentHolder(View itemView) {
                super( itemView );
                tv_name = itemView.findViewById( R.id.tv_name );
                tv_reason = itemView.findViewById( R.id.tv_reason );
                img = itemView.findViewById( R.id.img );
                img_vision = itemView.findViewById( R.id.img_vision );
                img_diopter = itemView.findViewById( R.id.img_diopter );
                img_axis = itemView.findViewById( R.id.img_axis );
                img_other = itemView.findViewById( R.id.img_other );
                container = itemView.findViewById( R.id.container );
                line = itemView.findViewById( R.id.line );
                ll_vision = itemView.findViewById( R.id.ll_vision );
                ll_diopter = itemView.findViewById( R.id.ll_diopter );
                ll_axis = itemView.findViewById( R.id.ll_axis );
                ll_other = itemView.findViewById( R.id.ll_other );
                ll_reason = itemView.findViewById( R.id.ll_reason );
//                examinationDate = itemView.findViewById(R.id.examinationDate);

            }
        }

        class LetterHolder extends RecyclerView.ViewHolder {
            TextView tv_name;

            LetterHolder(View itemView) {
                super( itemView );
                tv_name = itemView.findViewById( R.id.tv_name );
            }
        }
    }

    /**
     * 获取学生列表
     *
     * @time 2020/5/29 17:55
     */
    private void getStudentList(int status) {
        RestProxy.getInstance().getStudentList( taskId, classId, status + "", "", new Observer<StudentResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StudentResponse studentResponse) {
                className.setText( studentResponse.data.className );
                if (studentResponse.data.axisOption != null) {
                    hasAxisExamineOption = studentResponse.data.axisOption.hasAxisExamineOption;
                }
                if (studentResponse.data.otherOption != null) {
                    hasOtherExamineOption = studentResponse.data.otherOption.hasOtherExamineOption;
                }

                tv_status.setText( studentResponse.data.statisticsStr );
                for (Student s : studentResponse.data.classStudentList.list) {
                    try {
                        s.pinyin = Cn2Spell.getPinYin( s.studentName.trim() );
                        s.letter = s.pinyin.substring( 0, 1 ).toUpperCase();
                        if (!s.letter.matches( "[A-Z]" )) {
                            s.letter = "#";
                        }
                    } catch (Exception e) {
                        s.letter = "#";
                    }
                }

                list.clear();
                list.addAll( studentResponse.data.classStudentList.list );
                Collections.sort( list );
                listWithLetter();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                refreshLayout.finishRefresh();
                NetUtil.onError( e, mContext );
            }

            @Override
            public void onComplete() {

            }
        } );
    }

    private void listWithLetter() {
        listWithLetter.clear();
        listLetter.clear();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                Student stu = new Student();
                stu.letter = list.get( 0 ).letter;
                stu.type = 1;
                listWithLetter.add( stu );
                listWithLetter.add( list.get( 0 ) );
                listLetter.add( stu );
            } else if (listWithLetter.get( listWithLetter.size() - 1 ).letter.equals( list.get( i ).letter )) {
                listWithLetter.add( list.get( i ) );
            } else {
                Student stu = new Student();
                stu.letter = list.get( i ).letter;
                stu.type = 1;
                listWithLetter.add( stu );
                listWithLetter.add( list.get( i ) );
                listLetter.add( stu );
            }
        }
        myAdapter.notifyDataSetChanged();
        myLetterAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
    }


    class MyLetterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new LetterHolder( getLayoutInflater().inflate( R.layout.item_right_letter, parent, false ) );
        }

        @Override
        public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
            ((LetterHolder) holder).tv_name.setText( listLetter.get( position ).letter );
            if (listLetter.get( position ).rightLetterChoose == 1) {
                ((LetterHolder) holder).tv_name.setTextColor( ContextCompat.getColor( requireContext(), R.color.white ) );
                ((LetterHolder) holder).tv_name.setBackgroundResource( R.drawable.circle_blue );
            } else {
                ((LetterHolder) holder).tv_name.setTextColor( ContextCompat.getColor( requireContext(), R.color.commonBlack ) );
                ((LetterHolder) holder).tv_name.setBackgroundColor( Color.parseColor( "#00000000" ) );
            }
            holder.itemView.setOnClickListener( v -> {

                for (int i = 0; i < listWithLetter.size(); i++) {
                    if (listWithLetter.get( i ).type == 1 && listWithLetter.get( i ).letter.equals( listLetter.get( position ).letter )) {
                        smoothMoveToPosition( recyclerView_student_list, i );
                    }
                }

                for (Student stu : listLetter) {
                    stu.rightLetterChoose = 0;
                }
                listLetter.get( position ).rightLetterChoose = 1;
                notifyDataSetChanged();
            } );

        }

        @Override
        public int getItemCount() {
            return listLetter.size();
        }


        class LetterHolder extends RecyclerView.ViewHolder {
            TextView tv_name;

            LetterHolder(View itemView) {
                super( itemView );
                tv_name = itemView.findViewById( R.id.tv_name );
            }
        }
    }

    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition( mRecyclerView.getChildAt( 0 ) );
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition( mRecyclerView.getChildAt( mRecyclerView.getChildCount() - 1 ) );
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition( position );
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt( movePosition ).getTop();
                mRecyclerView.smoothScrollBy( 0, top );
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition( position );
            mToPosition = position;
            mShouldScroll = true;
        }
    }
}
